<script setup lang="ts">
import { ElLoading, ElNotification } from "element-plus";
import { nextTick, onMounted, reactive, ref, watch } from "vue";
import defaultPic from "@imgs/user_default.webp";
import moment from "moment";
import request from "@api";
import _debounce from "loadsh/debounce";

const emit = defineEmits({
  changeUnRead: null,
});
let replyer = ref({});
let sender = ref({});
let show = ref(false);
let messageList = ref([]);
let contextRef = ref();
const websocket = ref();
let text = ref("");
let loading: any;
let isClosed: boolean;
let listQuery = reactive({
  pageSize: 10,
  pageNum: 1,
  replyerId: null,
  senderId: null,
});
let historyScrollHeight: any = null;
let finished = false;
let addScrollDis = ref(0);

function connectWebsocket() {
  websocket.value = new WebSocket("ws://127.0.0.1:6580/" + replyer.value.id);

  websocket.value.onopen = function () {
    // console.log("websocket open");
  };

  websocket.value.onclose = function () {
    isClosed = true;
    loading && loading.close();
    // console.log("websocket close");
  };

  websocket.value.onmessage = function (ev: any) {
    let res = JSON.parse(ev.data);

    if (res.replyerId) {
      messageList.value.push(res);
    } else {
      let index = messageList.value.findIndex((v) => v.id == res.data);
      if (index == -1) return;
      if (res.code == 200) {
        messageList.value[index].isSend = null;
      } else {
        messageList.value[index].isSend = 2;
      }
    }
    nextTick(() => {
      addScrollDis.value =
        addScrollDis.value +
        contextRef.value.lastElementChild.clientHeight +
        20;

      contextRef.value.scrollTop =
        contextRef.value.clientHeight + addScrollDis.value;
    });
  };
}

function send() {
  if (text.value.length > 200) {
    return ElNotification({
      title: "Warning",
      message: "长度已超出",
      type: "warning",
    });
  }
  let id: any = Date.now();
  websocket.value.send(
    JSON.stringify({
      replyer: replyer.value,
      sender: sender.value,
      text: text.value,
      id,
    })
  );
  let item: any = {
    id,
    senderId: sender.value.id,
    replyerId: replyer.value.id,
    context: text.value,
    createTime: moment(Date.now()).format("YYYY-MM-DD HH-mm:ss"),
    isSend: 1, // 1 为正在发送  2 为发送失败   null 为发送成功
  };
  messageList.value.push(item);
  text.value = "";
  nextTick(() => {
    contextRef.value.scrollTop = contextRef.value.clientHeight;
  });
}

function init(replyerArg: object, senderArg: object) {
  if (!replyerArg) return console.log(new Error("replyer is require"));
  if (!senderArg) return console.log(new Error("sender is require"));
  if (!(replyerArg instanceof Object))
    return console.log(new Error("replyer is Object"));
  if (!(senderArg instanceof Object))
    return console.log(new Error("sender is Object"));
  document.querySelector(".session").style.display = "block";
  setTimeout(() => {
    isClosed = false;
    show.value = true;
    finished = false;
    addScrollDis.value = 0;
    replyer.value = replyerArg;
    sender.value = senderArg;
    listQuery.pageNum = 1;
    listQuery.replyerId = replyer.value.id;
    listQuery.senderId = sender.value.id;
    messageList.value = [];
    connectWebsocket();
    getMessageList();
    emit("changeUnRead", replyer.value.id);
  }, 50);
}

function close() {
  if (!isClosed) {
    loading = ElLoading.service({
      lock: true,
      text: "正在结束当前会话...",
      background: "rgba(0, 0, 0, 0.7)",
    });
  }
  websocket.value.close();
  websocket.value = null;
  setTimeout(() => {
    document.querySelector(".session").style.display = "none";
  }, 1000);
}

function getMessageList() {
  request["check/getMessageList"]({ params: { ...listQuery } }).then(
    (res: any) => {
      if (res.code == 200) {
        messageList.value = [...res.data.list.reverse(), ...messageList.value];
        listQuery.pageNum = res.data.pageNum;
        if (messageList.value.length >= res.data.total) {
          finished = true;
        }
        nextTick(() => {
          contextRef.value.scrollTop = contextRef.value.clientHeight;
          if (historyScrollHeight) {
            contextRef.value.scrollTop =
              contextRef.value.scrollHeight - historyScrollHeight;
          }
        });
      }
    }
  );
}

const scrollFunc = _debounce(function (e: any) {
  if (e.target.scrollTop < 50 && !finished) {
    historyScrollHeight = e.target.scrollHeight;
    listQuery.pageNum++;
    getMessageList();
  }
}, 500);

onMounted(() => {
  document.querySelector(".contextRef")?.addEventListener("scroll", scrollFunc);
});

defineExpose({
  init,
  close,
});
</script>

<template>
  <div class="mark" v-if="show" @click.self="close(), (show = false)"></div>
  <div class="session" :class="{ showSession: show }">
    <div class="name">
      {{ replyer.username || replyer.phoneNumber }}
      <i class="iconfont icon-cuo" @click="close(), (show = false)"></i>
    </div>
    <div class="content contextRef" ref="contextRef">
      <div class="item_context" v-for="item in messageList" :key="item.id">
        <template v-if="item.senderId == sender.id">
          <div class="item_right">
            <div class="left">
              <div class="top_tool">
                {{ sender.username || sender.phoneNumber }}
              </div>
              <div class="context">
                {{ item.context }}
                <i
                  v-if="item.isSend == 1"
                  class="iconfont icon-jiazai isLoading"
                ></i>
                <i
                  v-if="item.isSend == 2"
                  class="iconfont icon-jinggao isError"
                ></i>
              </div>
              <div class="create_time">{{ item.createTime }}</div>
            </div>
            <div class="right">
              <img :src="sender.userPic || defaultPic" alt="" />
            </div>
          </div>
        </template>
        <template v-else>
          <div class="item_left">
            <div class="left">
              <img :src="replyer.userPic || defaultPic" alt="" />
            </div>
            <div class="right">
              <div class="top_tool">
                {{ replyer.username || replyer.phoneNumber }}
              </div>
              <div class="context">
                {{ item.context }}
                <i
                  v-if="item.isSend == 1"
                  class="iconfont icon-jiazai isLoading"
                ></i>
                <i
                  v-if="item.isSend == 2"
                  class="iconfont icon-jinggao isError"
                ></i>
              </div>
              <div class="create_time">{{ item.createTime }}</div>
            </div>
          </div>
        </template>
      </div>
    </div>
    <div class="send_box">
      <el-input
        v-model="text"
        resize="none"
        :rows="2"
        type="textarea"
        maxlength="200"
        show-word-limit
        placeholder="内容"
      />
      <div class="btn_box">
        <el-button size="small" type="primary" @click="send">发送</el-button>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@keyframes rotation {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
.mark {
  position: fixed;
  top: 0px;
  left: 0px;
  bottom: 0px;
  right: 0px;
}
.session {
  display: none;
  z-index: 999;
  position: absolute;
  right: -400px;
  bottom: 100px;
  width: 350px;
  height: 530px;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 0 0 3px 2px #ededed;
  transition: all 0.3s;
  .name {
    height: 50px;
    line-height: 50px;
    text-align: center;
    font-weight: bold;
    font-size: 18px;
    padding: 0 25px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    box-shadow: 0 0 3px 2px #ededed;
    position: relative;
    i {
      font-size: 18px;
      position: absolute;
      top: 0px;
      right: 5px;
      cursor: pointer;
      user-select: none;
    }
  }
  .content {
    // padding: 15px 0;
    height: 360px;
    overflow-y: auto;
    background-color: #ededed;
    .item_right {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 20px;
      padding: 0 10px;
      .left {
        position: relative;
        padding-right: 10px;
        .top_tool {
          text-align: right;
          font-size: 12px;
          color: #6e7172;
        }
        .context {
          text-align: left;
          font-size: 14px;
          max-width: 250px;
          word-break: break-all;
          background-color: #7d84fe;
          color: #fff;
          padding: 5px;
          border-radius: 5px;
          position: relative;
          i {
            position: absolute;
            top: 30%;
            left: -20px;
            // transform: translate(-50%, -50%);
          }
          .isLoading {
            color: #7d84fe;
            margin-right: 0 !important;

            display: inline-block;
            transform-origin: center;
            animation: rotation 1s linear infinite;
          }
          .isError {
            font-weight: bold;
            color: #c30000;
          }
        }
        .create_time {
          font-size: 12px;
          color: #999;
          display: none;
          position: absolute;
          right: 10px;
          bottom: -16px;
          white-space: nowrap;
        }
      }
      .right {
        img {
          width: 40px;
          height: 40px;
        }
      }
      &:hover {
        .create_time {
          display: block;
        }
      }
    }

    .item_left {
      display: flex;
      justify-content: flex-start;
      margin-bottom: 20px;
      padding: 0 10px;
      .right {
        position: relative;
        padding-left: 10px;
        .top_tool {
          text-align: left;
          font-size: 12px;
          color: #6e7172;
        }
        .context {
          text-align: right;
          font-size: 14px;
          padding: 5px 0;
          max-width: 250px;
          word-break: break-all;
          background-color: #fff;
          padding: 5px;
          border-radius: 5px;
          color: #171a1d;
          position: relative;
          i {
            position: absolute;
            top: 30%;
            right: -20px;
            // transform: translate(-50%, -50%);
          }
          .isLoading {
            color: #7d84fe;
            margin-right: 0 !important;

            display: inline-block;
            transform-origin: center;
            animation: rotation 1s linear infinite;
          }
          .isError {
            font-weight: bold;
            color: #c30000;
          }
        }
        .create_time {
          font-size: 12px;
          color: #999;
          display: none;
          position: absolute;
          left: 10px;
          bottom: -16px;
          white-space: nowrap;
        }
      }
      .left {
        img {
          width: 40px;
          height: 40px;
        }
      }
      &:hover {
        .create_time {
          display: block;
        }
      }
    }
  }
  .send_box {
    box-shadow: 0 0 3px 2px #ededed;
    padding: 5px;
    height: 120px;
    :deep() .el-textarea__inner {
      box-shadow: none;
      height: 80px;
    }
    .btn_box {
      text-align: right;
      .el-button {
        border: none;
      }
    }
  }
}
.showSession {
  right: 100px;
}
</style>